using System;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Net;
using System.Xml;
using CKS.EBE.API;
using Microsoft.SharePoint;
using System.IO;
using Microsoft.SharePoint.WebControls;

namespace CKS.EBE.WebControls
{
    public class BlogImport : SPControl
    {
        TextBox _feedUrl;

        protected override void OnInit(EventArgs e)
        {
            EnsureChildControls();
            base.OnInit(e);
        }

        protected override void CreateChildControls()
        {
            _feedUrl = new TextBox();
            Controls.Add(_feedUrl);

            Button b = new Button();
            b.Click += new EventHandler(Import_Click);
            b.Text = "Import";
            Controls.Add(b);

            base.CreateChildControls();
        }

        protected string ExtractAndReplaceBinaries(string body)
        {
            //HtmlDocument oDoc = new HtmlDocument();
            //oDoc.LoadHtml(body);

            //HtmlNodeCollection oImages = oDoc.DocumentNode.SelectNodes("//img");
            //if (oImages != null)
            //{
            //    foreach (HtmlNode nImage in oImages)
            //    {
            //        string sUrl = nImage.GetAttributeValue("src", "");
            //        string sNewUrl = AddImage(sUrl);
            //        nImage.SetAttributeValue("src", sNewUrl);
            //    }
            //}

            //return oDoc.ToString();

            return "";
        }

        protected SPWeb Web
        {
            get { return SPContext.Current.Web; }
        }

        protected string AddImage(string url)
        {
            WebRequest oRequest = WebRequest.Create(url);
            WebResponse oReponse = oRequest.GetResponse();

            SPList oBinaries = Web.Lists[Localization.GetListName(Localization.BlogList.Binaries, Web.Language)];
            SPFolder oRoot = oBinaries.RootFolder;
            // Should we use dub folders?

            string sFilename = url.Substring(url.LastIndexOf('/'));
            Stream s = oReponse.GetResponseStream();
            byte[] oArray = new byte[s.Length];

            s.Read(oArray, 0, (int)s.Length);

            SPFile oFile = oRoot.Files.Add(sFilename, oArray);

            oReponse.Close();

            return oFile.Url;

        }

        void Import_Click(object sender, EventArgs e)
        {
            try
            {
                //CookComputing.XmlRpc.MetaBlogAPI.MetaBlogAPI oApi = new CookComputing.XmlRpc.MetaBlogAPI.MetaBlogAPI();
                //oApi.Url = "http://blog.thekid.me.uk/blogs/metablog.ashx";
                ////UserBlog[] arBlogs = oApi.GetUsersBlogs("Vince", "VinceRothwell", "nope");
                //RecentPost[] arPosts = oApi.GetRecentPosts("thekid", "vincerothwell", "nope", 60);

                XmlDocument oDoc = new XmlDocument();

                System.IO.StreamReader sr = System.IO.File.OpenText("c:\\posts.xml");
                string sXML = sr.ReadToEnd();
                sr.Close();

                oDoc.Load("c:\\posts.xml");


                //HttpWebRequest oRequest = (HttpWebRequest)HttpWebRequest.Create(_feedUrl.Text);
                //HttpWebResponse oResponse = (HttpWebResponse)oRequest.GetResponse();

                //System.IO.StreamReader sr = new System.IO.StreamReader(oResponse.GetResponseStream());
                //string sResponse = sr.ReadToEnd();

                //XmlDocument oDoc = new XmlDocument();
                //oDoc.LoadXml(sResponse);

                XmlNodeList oList = oDoc.SelectNodes("//param/value/array/data/value/struct");

                SPList oPosts = Web.Lists[Localization.GetListName(Localization.BlogList.Posts, Web.Language)];
                SPList oCategories = Web.Lists[Localization.GetListName(Localization.BlogList.Categories, Web.Language)];

                foreach (XmlElement oItem in oList)
                {
                    SPListItem oListItem = oPosts.Items.Add();

                    oListItem["Title"] = oItem.SelectSingleNode("member[name='title']/value/string").InnerText;

                    string sBody = oItem.SelectSingleNode("member[name='description']/value/string").InnerText;

                    oListItem["Body"] = sBody; // ExtractAndReplaceBinaries(sBody);


                    string sPubDate = oItem.SelectSingleNode("member[name='dateCreated']/value/dateTime.iso8601").InnerText;
                    //DateTime d;
                    DateTime d = new DateTime(int.Parse(sPubDate.Substring(0, 4)), int.Parse(sPubDate.Substring(4, 2)), int.Parse(sPubDate.Substring(6, 2)), int.Parse(sPubDate.Substring(9, 2)), int.Parse(sPubDate.Substring(12, 2)), int.Parse(sPubDate.Substring(15, 2)));
                    oListItem["PublishedDate"] = d;

                    oListItem.ModerationInformation.Status = SPModerationStatusType.Approved;

                    SPFieldLookupValueCollection c = new SPFieldLookupValueCollection();
                    XmlNodeList oCats = oItem.SelectNodes("member[name='categories']/value/array/data/value/string");
                    foreach (XmlElement oCat in oCats)
                    {
                        string sCategory = oCat.InnerText;

                        int id = -1;

                        foreach (SPListItem i in oCategories.Items)
                        {
                            if (((string)i["Title"]).ToLower() == sCategory.ToLower())
                            {
                                id = i.ID;
                                break;
                            }
                        }
                        
                        if (id == -1)
                        {
                            SPListItem oCatItem = oCategories.Items.Add();
                            oCatItem["Title"] = sCategory;
                            oCatItem.Update();
                            oCatItem = oCategories.Items[oCatItem.UniqueId];
                            id = oCatItem.ID;
                        }

                        c.Add(new SPFieldLookupValue(id, sCategory));
                    }
                    oListItem["Categories"] = c;

                    oListItem.Update();

                    PostEventReceiver.UpdateTitleForUrl(oListItem);

                }
            }
            catch (Exception ex)
            {
                Trace.Write(ex);
            }
        }
    }
}
